<template>
  <flexbox
    :style="{ height: contentHeight + 'px' }"
    class="main"
    orient="vertical"
    align="stretch"
  >
    <div class="title">
      <el-button
        style="padding: 8px 22px;border-radius:2px;"
        @click="handleCancel"
        >返回</el-button
      >
    </div>
    <el-container class="wrapper">
      <el-aside class="left">
        <ul class="list-wrapper">
          <li
            v-for="item in fieldList"
            :key="item.id"
            :class="{
              'fieLd-item-active': item.name == movedItemIndex,
              'field-item': true,
              'no-edit':
                editItemIndex != '' ? item.name != editItemIndex : false
            }"
            @click="() => (editItemIndex == '' ? handleClick(item) : '')"
          >
            <span>{{ item.name }}</span>
          </li>
          <!-- <draggable
            :list="fieldList"
            :clone="handleMove"
            class="list-wrapper"
            @end="handleEnd"
          >
          </draggable> -->
        </ul>
      </el-aside>
      <!-- <el-container v-loading="loading" class="content">
        <el-main>
          <draggable
            :list="fieldArr"
            :options="{
              group: 'list',
              forceFallback: true,
              fallbackClass: 'draggingStyle'
            }"
            @end="handleListMove"
          >
            <component
              v-for="(item, index) in fieldArr"
              :class="{ selected: selectedIndex == index }"
              :is-show="
                selectedIndex == index &&
                  (item.operating == null ||
                    item.operating == 0 ||
                    item.operating == 2)
              "
              :key="index"
              :attr="item"
              :is="item | typeToComponentName"
              @delete="handleDelete(item, index)"
              @select="handleChildSelect"
              @click.native="handleSelect(item, index)"
            />
          </draggable>
          <p v-if="fieldArr.length == 0" class="no-list">
            从左侧点击或拖拽来添加字段
          </p>
        </el-main>
      </el-container> -->
      <el-aside class="right" width="910px">
        <!-- <div class="mini-title">字段属性</div> -->
        <field-info
          v-if="form"
          :field="form"
          :can-transform="canTransform"
          :transform-data="transformData"
          :can-unique="canUnique"
          @selectAllSubmit="selectAllSubmit"
        />
        <div
          class="float-right"
          style="margin-bottom: 50px; padding-right: 20px;"
        >
          <el-button
            v-debounce="handleCancel"
            style="padding: 8px 22px;border-radius:2px;"
            >取消</el-button
          >
          <el-button
            v-debounce="handleSave"
            type="primary"
            style="padding: 8px 22px;border-radius:2px;"
            >保存</el-button
          >
        </div>
      </el-aside>
    </el-container>
  </flexbox>
</template>

<script>
import {
  customFieldHandleAPI,
  oaFieldHandleAPI,
  customFieldListAPI
} from "@/api/admin/crm";
import { filedGetFieldAPI } from "@/api/crm/common";
import {
  SingleLineText,
  MultiLineText,
  SelectForm,
  CheckboxForm,
  FileForm,
  TableForm
} from "./components/Fields";
import draggable from "vuedraggable";

import crmTypeModel from "@/views/crm/model/crmTypeModel";
import Field from "./model/field";
import FieldList from "./model/fieldList";
import FieldInfo from "./components/FieldInfo";
import {
  objDeepCopy,
  regexIsCRMMobile,
  regexIsCRMEmail,
  regexIntNumber,
  regexIsCRMNumber,
  regexIsCRMMoneyNumber
} from "@/utils";

export default {
  name: "Handlefield",
  components: {
    SingleLineText,
    MultiLineText,
    SelectForm,
    CheckboxForm,
    FileForm,
    TableForm,
    draggable,
    FieldInfo
  },
  filters: {
    /** 根据type 找到组件 */
    typeToComponentName(item) {
      if (
        item.formType === "text" ||
        item.formType === "number" ||
        item.formType === "floatnumber" ||
        item.formType === "mobile" ||
        item.formType === "email" ||
        item.formType === "date" ||
        item.formType === "datetime" ||
        item.formType === "single_user" ||
        item.formType === "structure" ||
        item.formType === "contacts" ||
        item.formType === "customer" ||
        item.formType === "contract" ||
        item.formType === "business" ||
        item.formType === "single_user" ||
        item.formType === "number_input" ||
        item.type == 0
      ) {
        return "SingleLineText";
      } else if (item.formType === "textarea") {
        return "MultiLineText";
      } else if (item.formType === "select") {
        return "SelectForm";
      } else if (item.formType === "checkbox") {
        return "CheckboxForm";
      } else if (item.formType === "file") {
        return "FileForm";
      } else if (item.formType === "form") {
        return "TableForm";
      } else if (item.formType === "payment_type") {
        return "SelectForm";
      }
    }
  },
  data() {
    return {
      fieldList: [],
      fieldArr: [], // 数据没有返回时 根据null 判断不能操作
      movedItem: {},
      movedItemIndex: "", // 选择的字段标识
      editItemIndex: "", // 标记的字段标识
      selectedIndex: -1,
      rejectHandle: true, // 请求未获取前不能操作
      /** 右边展示数据 */
      form: null, // operating 0 改删 1改 2删 3无
      loading: false, // 加载动画
      // 展示表单预览
      tablePreviewData: { types: "", id: "" },
      showTablePreview: false,
      contentHeight: document.documentElement.clientHeight - 75,
      // 转移匹配字段源
      transformData: null,
      isOnec: true // 默认第一次添加字段
    };
  },
  computed: {
    // 能转移
    canTransform() {
      return this.moduleType == "crm_leads";
    },
    canUnique() {
      return this.moduleType != "oa_examine"; // 办公审批不允许设置唯一
    },
    moduleType() {
      return this.$route.params.type; // oa_examine
    }
  },
  watch: {
    selectedIndex: {
      handler(newVal) {
        if (newVal >= 0) {
          this.form = this.fieldArr[newVal];
        } else {
          this.form = null;
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.getFieldList();
  },
  mounted() {
    window.onresize = () => {
      this.contentHeight = document.documentElement.clientHeight - 75;
    };
    // 获取当前模块的自定义数据
    this.getCustomInfo(this.$route.params);

    // 配置转移字段
    if (this.canTransform) {
      this.getTransformField();
    }
  },
  methods: {
    /**
     * 获取字段
     */
    getFieldList() {
      this.fieldList = FieldList;
    },

    /**
     * 获取当前模块的自定义数据
     */
    getCustomInfo(info) {
      this.loading = true;
      let request = customFieldListAPI;
      var params = {};

      if (info.label !== "none") {
        params.label = info.label;
      }
      request(params, { isQueryFieldType: false })
        .then(res => {
          this.rejectHandle = false;
          for (let index = 0; index < res.data.length; index++) {
            const element = res.data[index];
            if (
              element.formType == "select" ||
              element.formType == "checkbox"
            ) {
              var temps = [];
              for (let i = 0; i < element.setting.length; i++) {
                // 必须有属性 才能for绑定 所以处理了下数据
                const item = element.setting[i];
                temps.push({ value: item });
              }
              element.showSetting = temps; // 放到showSeeting上

              // 删除无效的多选默认值
              if (element.formType == "checkbox") {
                element.defaultValue = element.defaultValue.filter(item => {
                  return element.setting.indexOf(item) != -1;
                });
              }
            }
            element.isNull = element.isNull == 1;
            element.isUnique = element.isUnique == 1;
            element.isHidden = element.isHidden == 1; // 隐藏字段
          }
          this.fieldArr = res.data;
          // 有编辑字段下标
          if (info.index != undefined) {
            this.selectedIndex = info.index; // 编辑字段的下标
            this.form = this.fieldArr[info.index]; // 回显指定编辑字段的值
            // 找到编辑字段的标签元素项，将其他标签不可选中，且当前标签元素不可点击
            for (let i = 0; i < this.fieldList.length; i++) {
              if (this.fieldList[i].formType == info.formType) {
                this.editItemIndex = this.fieldList[i].name; // 存储编辑字段标识
                this.movedItemIndex = this.fieldList[i].name;
              }
            }
          } else {
            // 新建字段 默认选择标签元素第一项
            this.handleClick(this.fieldList[0]);
          }
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /**
     * 删除一行自定义数据
     */
    handleDelete(item, index) {
      this.$confirm("确定删除该自定义字段吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.fieldArr.splice(index, 1);
          this.$nextTick(() => {
            this.selectedIndex = -1;
          });
        })
        .catch(() => {});
    },

    /**
     * 主列表的选择
     */
    handleSelect(item, index) {
      this.selectedIndex = index;
      if (this.selectedIndex === index) {
        // 表自定义字段的刷新
        if (index >= 0) {
          this.form = this.fieldArr[index];
        }
      }
    },

    /**
     * 表的选择
     */
    handleChildSelect(data) {
      this.form = data.data;
    },

    /**
     * 保存数据
     */
    handleSave() {
      if (this.rejectHandle) return;

      var tempFieldArr = objDeepCopy(this.fieldArr);
      const names = []; // 判断名称重复
      const limitFields = "select|update|union|and|or|delete|insert|trancate|char|substr|ascii|declare|exec|count|master|into|drop|execute".split(
        "|"
      );
      for (let index = 0; index < tempFieldArr.length; index++) {
        const item = tempFieldArr[index];
        item.isNull = item.isNull == true ? 1 : 0;
        item.isUnique = item.isUnique == true ? 1 : 0;
        item.isHidden = item.isHidden == true ? 1 : 0;
        if (item.name !== "" && item.name !== null && item.name !== undefined) {
          item.name = item.name.trim();

          if (limitFields.includes(item.name)) {
            this.$message({
              message: `[${
                item.name
              }]自定义字段标识名与系统字段重复，请使用其他字段！`,
              type: "error"
            });
            return;
          } else if (names.includes(item.name)) {
            this.$message({
              message: `第${index + 1}行[${item.name}]自定义字段标识名重复`,
              type: "error"
            });
            return;
          } else {
            names.push(item.name);
          }
        }
        if (!item.name) {
          this.$message({
            type: "error",
            message: `第${index + 1}行自定义字段，标识名不能为空`
          });
          return;
        } else if (item.formType == "select" || item.formType == "checkbox") {
          var temps = [];
          for (let i = 0; i < item.showSetting.length; i++) {
            const element = item.showSetting[i];
            if (element.value) {
              temps.push(element.value);
            }
          }
          item.options = temps.join(",");
          if (item.formType == "checkbox") {
            item.defaultValue = item.defaultValue.join(",");
          }
        } else if (item.formType == "mobile" && item.defaultValue) {
          if (!regexIsCRMMobile(item.defaultValue)) {
            this.$message({
              message: `第${index + 1}行（${
                item.name
              }）自定义字段输入的默认值手机格式有误`,
              type: "error"
            });
            return;
          }
        } else if (item.formType == "email" && item.defaultValue) {
          if (!regexIsCRMEmail(item.defaultValue)) {
            this.$message({
              message: `第${index + 1}行（${
                item.name
              }）自定义字段输入的默认值邮箱格式有误`,
              type: "error"
            });
            return;
          }
        } else if (item.formType == "number_input" && item.defaultValue) {
          if (!regexIntNumber(item.defaultValue)) {
            this.$message({
              message: `第${index + 1}行（${
                item.name
              }）自定义字段输入的默认值数值格式有误`,
              type: "error"
            });
            return;
          }
        } else if (item.formType === "number" && item.defaultValue) {
          if (!regexIsCRMNumber(item.defaultValue)) {
            this.$message({
              message: `第${index + 1}行（${
                item.name
              }）自定义字段输入的默认值数字格式有误`,
              type: "error"
            });
            return;
          }
        } else if (item.formType == "floatnumber" && item.defaultValue) {
          if (!regexIsCRMMoneyNumber(item.defaultValue)) {
            this.$message({
              message: `第${index + 1}行（${
                item.name
              }）自定义字段输入的默认值货币格式有误`,
              type: "error"
            });
            return;
          }
        }

        item.type = this.getTypeFromFormType(item.formType);
      }
      this.loading = true;
      var params = {};
      params.data = tempFieldArr;
      if (this.$route.params.label !== "none") {
        params.label = this.$route.params.label;
      }
      if (this.moduleType === "oa_examine") {
        params.categoryId = this.$route.params.id;
      }
      for (const item of params.data) {
        for (const key in item) {
          if (JSON.stringify(item[key]) == "{}") {
            item[key] = null;
          }
        }
      }

      // 请求
      const request =
        {
          oa_examine: oaFieldHandleAPI
        }[this.moduleType] || customFieldHandleAPI;
      // console.log(params, this.fieldArr);
      request(params)
        .then(res => {
          if (res && (res.code == 0 || res.code == 200)) {
            this.$message({
              type: "success",
              message: "操作成功"
            });
            this.handleCancel();
          }
          this.loading = false;
          // this.getCustomInfo();
        })
        .catch(() => {
          this.loading = false;
          // this.getCustomInfo();
        });
    },

    // 设置type
    getTypeFromFormType(formType) {
      return (
        {
          text: 1,
          textarea: 2,
          select: 3,
          radio: 3,
          date: 4,
          number_input: 29,
          number: 5,
          floatnumber: 6,
          mobile: 7,
          file: 8,
          checkbox: 9,
          structure: 12,
          datetime: 13,
          email: 14,
          customer: 15,
          student: 40,
          business: 16,
          contacts: 17,
          map_address: 18,
          category: 19,
          contract: 20,
          receivables_plan: 21,
          single_user: 28,
          leve_linkage: 39
        }[formType] || "1"
      );
    },

    /**
     * 返回
     */
    handleCancel() {
      this.$router.go(-1);
    },

    /**
     * 从左侧移动到右侧
     */
    handleEnd(e) {
      if (!this.rejectHandle) {
        const newField = new Field({
          name: this.movedItem.name,
          formType: this.movedItem.formType
        });
        // 如果当前选中的table 则加入到table中
        if (
          this.form &&
          this.form.formType === "form" &&
          this.movedItem.formType !== "form"
        ) {
          this.form.formValue.push(newField);
        } else {
          // 第一次添加为新增
          if (this.isOnec) {
            this.fieldArr.push(newField);
            this.selectedIndex = this.fieldArr.length - 1;
            this.isOnec = false;
          } else {
            // 替换更改的字段
            this.fieldArr.splice(this.fieldArr.length - 1, 1, newField);
            this.selectedIndex = this.fieldArr.length - 1; // 取字段数组的最后一项，最后一项是新增的字段
            this.form = this.fieldArr[this.selectedIndex];
          }
        }
      }
    },

    /**
     * 从左侧移动到右侧 时候的数据对象
     */
    handleMove(obj) {
      this.movedItem = obj;
    },

    /**
     * 点击左侧进行添加
     */
    handleClick(obj) {
      console.log(obj);
      this.movedItem = obj;
      this.movedItemIndex = obj.name;
      this.handleEnd();
    },

    /**
     * list move
     */
    handleListMove(e) {
      this.selectedIndex = e.newIndex;
    },

    /**
     * 获取添加字段
     */
    getTransformField() {
      filedGetFieldAPI({
        label: crmTypeModel["customer"]
      })
        .then(res => {
          const data = {
            text: [],
            textarea: [],
            select: [],
            checkbox: [],
            number: [],
            floatnumber: [],
            mobile: [],
            email: [],
            date: [],
            datetime: [],
            user: [],
            structure: []
          };

          for (let index = 0; index < res.data.length; index++) {
            const element = res.data[index];
            const array = data[element.formType];
            if (array) {
              array.push({
                label: element.name,
                value: element.fieldId
              });
            }
          }

          this.transformData = data;
        })
        .catch(() => {});
    },

    // 多级下拉数据提交
    selectAllSubmit(data) {
      this.handleSave();
    }
  }
};
</script>

<style scoped lang="scss">
@import "@/styles/mixin.scss";

.el-form-item {
  margin: 0;
  padding-bottom: 16px;
  border-bottom: 1px solid $xr-border-line-color;
  .desc {
    color: #999;
    font-size: 12px;
  }
  &:last-child {
    margin-top: 15px;
  }
}

.title {
  padding: 0 16px;
  height: 55px;
  line-height: 60px;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  background-color: #fff;
  border-bottom: 1px solid $xr-border-line-color;
}

.wrapper {
  background-color: white;
  // border: 1px solid $xr-border-line-color;
  // border-radius: $xr-border-radius-base;
  min-width: 1000px;
  overflow: hidden;
  flex: 1;
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
  -khtml-user-select: none;
  user-select: none;
  .left {
    min-width: 310px;
    .mini-title {
      font-size: 14px;
      margin: 30px 0 20px 20px;
    }
    .list-wrapper {
      padding: 20px 0;
      margin: 15px;
      background-color: #f5f6fb;
      .field-item {
        height: 40px;
        font-size: 13px;
        padding: 0 20px;
        cursor: pointer;
        border-left: 2px solid transparent;
        @include left;
        .icon {
          color: #74b2f2;
          margin-right: 8px;
          width: 20px;
          height: 20px;
        }
      }
      .fieLd-item-active {
        border-left: 2px solid #0066f9;
        background-color: #edf1fc !important;
      }
      .no-edit {
        color: #cbcbcb;
      }
    }
  }

  .content {
    border-left: 1px solid $xr-border-line-color;
    border-right: 1px solid $xr-border-line-color;
    .el-header {
      border-bottom: 1px solid $xr-border-line-color;
      @include right;
    }
    .el-main {
      padding: 0;
      .selected {
        border-left: 2px solid $xr-color-primary;
        background: #f7f8fa;
      }
      .no-list {
        margin: 200px 0;
        color: #ccc;
        @include center;
      }
    }
  }

  .right {
    font-size: 14px;
    .mini-title {
      height: 60px;
      border-bottom: 1px solid $xr-border-line-color;
      padding-left: 20px;
      @include left;
    }
  }
}
</style>
